<?php
/**
 * BootAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using BootAdmin.
 *
 * @Author G.r<root@BootAdmin.com>
 */

declare (strict_types=1);

namespace app\admin\middleware;

use app\admin\service\Auth;
use app\common\traits\JumpTrait;
use think\helper\Str;

/**
 * 权限验证中间件
 */
class AuthMiddleware
{
    use JumpTrait;

    /**
     * @notes 权限验证
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle($request, \Closure $next)
    {
        //判断接口是否免登录
        $isNotNeedLogin = $request->controllerObject->isNotNeedLogin();
        if ($isNotNeedLogin) {
            return $next($request);
        }
        //判断接口是否需要鉴权
        $isNotNeedAuth = $request->controllerObject->isNotNeedAuth();
        // 需要鉴权
        if (!$isNotNeedAuth) {
            // 超级管理员无需鉴权
            if ($request->adminId == env('admin.super_admin')) {
                return $next($request);
            }
            // 路由地址
            $route = strtolower(str_replace('.', ':', $request->controller()) . ':' . $request->action());
            $routes = $this->formatUrl(Auth::getRules());
            // 验证权限
            if (!in_array($route, $routes)) {
                return $this->fail('无权限操作', [], 403);
            }
        }
        return $next($request);
    }

    /**
     * @notes 格式化URL
     * @param array $data
     * @return array|string[]
     */
    public function formatUrl(array $data)
    {
        return array_map(function ($item) {
            return strtolower(Str::camel($item));
        }, $data);
    }
}